(function(window,$){
    if (!window.WebSocket){
        alert("WebSocket not supported by this browser!");
    }
    //定义机器人scoket连接对象
    var robotSocket = {
        ws:null,
        listenerList:new Array(),
        regMethod:null,
        connectWS:function() {
            var self = this;
            if (this.ws == null) {
                this.ws = new WebSocket("ws://117.25.148.88:18181");
               // ws = new WebSocket("ws://echo.websocket.org/");
                this.ws.onmessage = function (evt) {
                    //循环检查是否有匹配的监听器。
                    // 如果不匹配，返回 -2
                    for(var i=0;i<robotSocket.listenerList.length;i++){
                        var result = robotSocket.listenerList[i].apply(robotSocket,[evt.data]);
                        // 如果匹配并执行成功，返回 0，继续下一个监听器执行
                        if(result==0 || result== -2){
                            continue;
                        }
                        // 如果匹配并执行成功，并不再让下一个监听器执行，返回 1
                        else if(result==1){ 
                            return;
                        }
                        // 如果匹配但执行不成功，返回 -1
                        else if(result==-1){
                            console.log("消息处理失败："+JSON.stringify(evt));
                        }
                    }
                    console.log("接收到信息:" + evt.data);
                };

                this.ws.onclose = function () {
                    alert("连接已关闭。");
                    this.ws = null;
                };

                this.ws.onerror = function (evt) {
                    alert("连接出错:" + evt.data);
                    this.ws = null;
                }

                this.ws.onopen = function (evt) {
                    alert("连接已打开。");
                    self.regMethod(evt);
                };
            }
        },
        //获取websocket对象
        getWs(){
          return this.ws;  
        },
        addListener:function (fn){
            robotSocket.listenerList.push(fn);
        },
        setRegMethod:function(fn){
            this.regMethod = fn;
        },
        sendMsg:function (jsonMsg) {
            if(this.ws==null){
                this.connectWS();
            }
            if (this.ws != null) {
                try {
                    var str = JSON.stringify(jsonMsg);
                    this.ws.send(str);
                } catch (err) {
                    console.log(JSON.stringify(err));
                    console.log(err.Data);
                }
            } else {
                console.log("连接失效。");
            }
        },
        closeWS:function () {
            this.ws.send("exit");
            this.ws.close();
        }
    };
   window.robotSocket = robotSocket;
})(window,jQuery);
